package com.example.myapplication.widget;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

import java.util.Calendar;

public class TimePickerActivity extends AppCompatActivity implements View.OnClickListener, TimePickerDialog.OnTimeSetListener {

    private TextView tvTime;

    private TimePicker timePicker;

    private TextView tvTimeFromDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_time_picker);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.btn_time_ok).setOnClickListener(this);
        tvTime = findViewById(R.id.tv_time);
        timePicker = findViewById(R.id.time_picker);

        findViewById(R.id.btn_open_time_dlg).setOnClickListener(this);
        tvTimeFromDialog = findViewById(R.id.tv_time_from_dlg);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_time_ok) {
            String desc = String.format("您选择的时间是：%d小时%d分钟", timePicker.getCurrentHour(), timePicker.getCurrentMinute());
            tvTime.setText(desc);
        } else if (v.getId() == R.id.btn_open_time_dlg) {
            // 通过时间对话框选择时间。第2个参数用于指定时间选择的方式和Spinner类似
            TimePickerDialog dialog = new TimePickerDialog(
                    this, android.R.style.Theme_Holo_Light_Dialog,
                    this, 12, 0, true);
            dialog.show();
        }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String desc = String.format("您选择的时间是：%d小时%d分钟", hourOfDay, minute);
        tvTimeFromDialog.setText(desc);
    }
}